import { createRouter, createWebHistory } from 'vue-router'
import { ref } from 'vue'

// 创建全局loading状态
const isLoading = ref(false)

const routes = [
  {
    path: '/',
    name: 'Home',
    component: () => import('../views/Home.vue')
  },
  {
    path: '/about',
    name: 'About',
    component: () => import('../views/About.vue')
  },
  // 404页面路由 - 捕获所有未匹配的路由
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: () => import('../views/NotFound.vue')
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 全局前置守卫 - 路由跳转前显示loading
router.beforeEach((_to, _from, next) => {
  isLoading.value = true
  next()
})

// 全局后置守卫 - 路由跳转完成后隐藏loading
router.afterEach(() => {
  // 添加短暂延迟让用户看到loading效果
  setTimeout(() => {
    isLoading.value = false
  }, 300)
})

// 全局错误守卫 - 路由错误时也隐藏loading
router.onError(() => {
  isLoading.value = false
})

// 导出loading状态和方法
export const useRouterLoading = () => ({
  isLoading,
})

export default router